package com.hsteach.service.rota;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.hsteach.common.core.page.TableDataInfo;
import com.hsteach.common.utils.DateUtils;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.dao.domain.rota.RotaDetail;
import com.hsteach.dao.mapper.rota.RotaDetailMapper;
import com.hsteach.enums.BooleanEnum;
import com.hsteach.web.controller.rota.vo.ListRotaVo;
import com.hsteach.web.dto.PageDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.hsteach.dao.mapper.rota.RotaMapper;
import com.hsteach.dao.domain.rota.Rota;

/**
 * 值班主表Service业务层处理
 *
 * @author fanxquer
 * @date 2023-10-18
 */
@Service
public class RotaService {
    @Autowired
    private RotaMapper rotaMapper;

    @Autowired
    private RotaDetailMapper rotaDetailMapper;

    /**
     * 查询值班主表
     *
     * @param id 值班主表主键
     * @return 值班主表
     */
    public Rota selectRotaById(Long id) {
        return rotaMapper.selectRotaById(id);
    }

    /**
     * 查询值班主表列表
     *
     * @param rota 值班主表
     * @return 值班主表
     */
    public List<Rota> selectRotaList(Rota rota) {
        return rotaMapper.selectRotaList(rota);
    }

    public Rota getOneNow() {
        return rotaMapper.getOneNow();
    }

    @Cacheable(cacheNames = "listRotaCache", key = "#personId")
    public TableDataInfo<ListRotaVo> listMyRotaCache(String personId) {
        PageDto pageDto = new PageDto();
        pageDto.setPageNum(1);
        pageDto.setPageSize(9999);
        TableDataInfo<ListRotaVo> ret = listRota(pageDto, BooleanEnum.FALSE.getCode());
        long l = System.currentTimeMillis();
        // 重新排序
        List<ListRotaVo> collect = ret.getRows().stream().sorted((v1, v2) -> {
            boolean v1r = false;
            boolean v2r = false;
            // 判断是否处于该值班表日期范围
            if (v1.getRotaBegin().getTime() <= l && v1.getRotaEnd().getTime() >= l) {
                v1r = true;
            }
            if (v2.getRotaBegin().getTime() <= l && v2.getRotaEnd().getTime() >= l) {
                v2r = true;
            }
            if (v1r && v2r) {
                return 1;
            } else {
                if (v1r) return -1;
                if (v2r) return 1;
            }
            // 如果没有在范围内，就时间最近的排前面
            if (v1.getRotaBegin().getTime() > l && v2.getRotaBegin().getTime() > l) {
                long dif1 = getDif(l, v1.getRotaBegin().getTime());
                long dif2 = getDif(l, v2.getRotaBegin().getTime());
                if (dif1 < dif2) {
                    return -1;
                } else {
                    return 1;
                }
            } else if (v1.getRotaBegin().getTime() > l) {
                return -1;
            } else {
                return 1;
            }
        }).collect(Collectors.toList());
        ret.setRows(collect);
        return ret;
    }

    public TableDataInfo<ListRotaVo> listRota(PageDto dto, Integer fileFlg) {
        Rota query = new Rota();
        query.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        query.setDelStatus(BooleanEnum.TRUE.getCode());
        query.setFileFlg(fileFlg);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Rota> rotas = rotaMapper.selectRotaList(query);
        Long total = new PageInfo(rotas).getTotal();
        Map<Long, List<RotaDetail>> countMap;
        if (rotas.size() > 0) {
            List<RotaDetail> rotaDetails = rotaDetailMapper.selectCountNotFile(SecurityUtils.getAuthInfo().getOrgCode(), rotas.stream().map(Rota::getId).collect(Collectors.toList()));
            countMap = rotaDetails.stream().collect(Collectors.groupingBy(RotaDetail::getRotaId));
        } else {
            countMap = Maps.newHashMap();
        }
        List<ListRotaVo> ret = rotas.stream().map(e -> {
            ListRotaVo vo = new ListRotaVo();
            BeanUtils.copyProperties(e, vo);
            if (vo.getRotaEnd().after(DateUtils.getNowyyyyMMdd())) {
                vo.setFileFlg(-1);
            }
//            if (countMap.containsKey(e.getId())) {
//                List<RotaDetail> rotaDetails = countMap.get(e.getId());
//                RotaDetail rotaDetail = rotaDetails.stream().filter(k -> BooleanEnum.FALSE.getCode().equals(k.getFileFlg())).findFirst().orElse(null);
//                if (rotaDetail != null && rotaDetail.getCount() > 0) {
//                    vo.setFileFlg(0);
//                } else {
//                    vo.setFileFlg(1);
//                }
//            } else {
//                vo.setFileFlg(-1);
//            }
            return vo;
        }).collect(Collectors.toList());

        TableDataInfo<ListRotaVo> tableDataInfo = new TableDataInfo(ret, total);

        return tableDataInfo;
    }

    private long getDif(long n1, long n2) {
        if (n1 > n2) {
            return n1 - n2;
        } else {
            return n2 - n1;
        }
    }

    public TableDataInfo<ListRotaVo> listFiled(PageDto dto) {
//        List<RotaDetail> countFiled = rotaDetailMapper.selectCountFile(SecurityUtils.getAuthInfo().getOrgCode());
//        List<Long> rotaIds = countFiled.stream().filter(e -> e.getCount() > 0).map(RotaDetail::getRotaId).collect(Collectors.toList());
//
//        if (rotaIds.size() == 0) {
//            return new TableDataInfo(Lists.newArrayList(), 0);
//        }
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        Rota query = new Rota();
        query.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        query.setDelStatus(BooleanEnum.TRUE.getCode());
        query.setFileFlg(BooleanEnum.TRUE.getCode());
//        query.setIds(rotaIds);
        List<Rota> rotas = rotaMapper.selectRotaList(query);
        Long total = new PageInfo(rotas).getTotal();

        List<ListRotaVo> ret = rotas.stream().map(e -> {
            ListRotaVo vo = new ListRotaVo();
            BeanUtils.copyProperties(e, vo);
            vo.setFileFlg(BooleanEnum.TRUE.getCode());
            return vo;
        }).collect(Collectors.toList());
        TableDataInfo<ListRotaVo> tableDataInfo = new TableDataInfo(ret, total);
        return tableDataInfo;
    }

    /**
     * 新增值班主表
     *
     * @param rota 值班主表
     * @return 结果
     */
    public int insertRota(Rota rota) {
        rota.setCreateTime(DateUtils.getNowDate());
        return rotaMapper.insertRota(rota);
    }

    /**
     * 修改值班主表
     *
     * @param rota 值班主表
     * @return 结果
     */
    public int updateRota(Rota rota) {
        rota.setUpdateTime(DateUtils.getNowDate());
        return rotaMapper.updateRota(rota);
    }

    /**
     * 批量删除值班主表
     *
     * @param ids 需要删除的值班主表主键
     * @return 结果
     */
    public int deleteRotaByIds(Long[] ids) {
        return rotaMapper.deleteRotaByIds(ids);
    }

    /**
     * 删除值班主表信息
     *
     * @param id 值班主表主键
     * @return 结果
     */
    public int deleteRotaById(Long id) {
        return rotaMapper.deleteRotaById(id);
    }
}
